package com.leoman.utils;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class JPushUtils {
    protected static final Logger LOG = LoggerFactory.getLogger(JPushUtils.class);

    public static final String APPKEY = "47664054c2791989cb05090a";
    public static final String SECRET = "7b1a2bc702a4ca0665d8d19e";
    public static final String ALERT = "你有一条新消息";

    public static JPushClient jpushClient = null;

    public static void main(String[] args) {
        try {
            sendMsgByRegistrationId("140fe1da9ea20472b88", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据设备号推送（批量）
     *
     * @param registrationId 设备号
     * @param maps           推送对象
     * @throws Exception
     */
    public static void sendMsgByRegistrationId(String registrationId, Map<String, Object> maps) throws Exception {
        // 生成推送的内容
        PushPayload payload = sendMsgToIOS(registrationId, maps);
        reSendPush(sendPush(payload), registrationId, maps);
    }

    public static void reSendPush(Integer result, String registrationId, Map<String, Object> map) {
        if (result == 1002) {
            PushPayload payload = sendMsgToAndroid(registrationId, map);
            sendPush(payload);
        }
    }

    /**
     * 发送所有用户
     *
     * @throws Exception
     */
    public static void sendMsgToAll() throws Exception {
        // 生成推送的内容
        PushPayload payload = sendALLAlert();
        sendPush(payload);
    }

    /*public static void reSendPush(Integer result, String registrationId, Map<String, Object> map) {
        if (result == 1002) {
            PushPayload payload = sendMsgToAll(registrationId, map);
            sendPush(payload);
        }
    }*/

    public static Integer sendPush(PushPayload payload) {
        PushResult result;
        Integer code = 0;
        try {
            jpushClient = new JPushClient(SECRET, APPKEY, 86400);
            result = jpushClient.sendPush(payload);
            System.out.println(result + "................................");
            LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            code = e.getErrorCode();
        }
        return code;
    }

    public static PushPayload sendALLAlert() {
        return PushPayload.newBuilder().setPlatform(Platform.all())// 设置接受的平台
                .setAudience(Audience.all())// Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
                .setOptions(Options.newBuilder().setApnsProduction(true).build()).setNotification(Notification.alert(ALERT)).build();
    }

    /**
     * 根据设备号id发送消息
     *
     * @param registrationId 设备号
     * @param map            消息体
     * @return
     */
    @SuppressWarnings({"unchecked"})
    public static PushPayload sendMsgToUserById(String registrationId, Map<String, Object> map) {
        String alertString;
        Map<String, String> extras = null;
        if (null == map) {
            alertString = ALERT;
        } else {
            alertString = map.get("alert").toString();
            extras = (Map<String, String>) map.get("extras");
        }

        return PushPayload.newBuilder().setPlatform(Platform.all())// 设置接受的平台
                .setAudience(Audience.registrationId(registrationId))// Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
                .setOptions(Options.newBuilder().setApnsProduction(true).build()).setNotification(Notification.newBuilder().addPlatformNotification(((IosNotification.Builder) IosNotification.newBuilder().setAlert(alertString).setSound("default").addExtras(extras)).build()).build()).build();
    }

    @SuppressWarnings({"unchecked"})
    public static PushPayload sendMsgToIOS(String registrationId, Map<String, Object> map) {
        String alertString;
        Map<String, String> extras = null;
        if (null == map) {
            alertString = ALERT;
        } else {
            alertString = map.get("alert").toString();
            extras = (Map<String, String>) map.get("extras");
        }

        return PushPayload.newBuilder().setPlatform(Platform.all())// 设置接受的平台
                .setAudience(Audience.registrationId(registrationId))// Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
                .setOptions(Options.newBuilder().setApnsProduction(true).build()).setNotification(Notification.ios(alertString, extras)).build();
    }

    @SuppressWarnings("unchecked")
    public static PushPayload sendMsgToAndroid(String registrationId, Map<String, Object> map) {
        String alertString;
        Map<String, String> extras = null;
        if (null == map) {
            alertString = ALERT;
        } else {
            alertString = map.get("alert").toString();
            extras = (Map<String, String>) map.get("extras");
        }

        return PushPayload.newBuilder().setPlatform(Platform.all())// 设置接受的平台
                .setAudience(Audience.registrationId(registrationId))// Audience设置为all，说明采用广播方式推送，所有用户都可以接收到
                .setOptions(Options.newBuilder().setApnsProduction(true).build()).setNotification(Notification.android(alertString, null, extras)).build();
    }
}